package com.lw.common.camera

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import kotlin.jvm.JvmOverloads
import androidx.fragment.app.FragmentActivity
import com.lxj.xpopup.XPopup
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.OnPermissionCallback
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File
import java.lang.Exception
import java.util.ArrayList

/**
 * 相机拍照、相册选择照片
 */
class SelectPictureManager
//        fileName = System.currentTimeMillis() + ".jpg";
// 默认使用时间戳作为图片名字
/**
 * 构造SelectPictureManager对象
 *
 * @param activity 上下文 这样就可以自主的实现
 */
@JvmOverloads constructor(

    var activity: FragmentActivity, //选择之后照片的回调监听
    var count: Int,
    var pictureSelectListener: PictureSelectListener? = null
) {
    /**
     * 构造SelectPictureManager对象
     *
     * @param activity              上下文
     * @param pictureSelectListener 回调监听
     */
    /**
     * 设置图片回调监听
     */
    @JvmName("setPictureSelectListener1")
    fun setPictureSelectListener(pictureSelectListener: PictureSelectListener?) {
        this.pictureSelectListener = pictureSelectListener
    }

    /**
     * 展示选择拍照的弹窗  一个是从相机选择 一个是拍照选择
     */
    fun showSelectPictureDialog() {
        // 这种弹窗从 1.0.0版本开始实现了优雅的手势交互和智能嵌套滚动
        XPopup.Builder(activity)
            .asBottomList("", arrayOf("从相册选择", "拍照")) { position: Int, _: String? ->
                if (position == 0) {
                    //从相册选择
                    getPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                } else if (position == 1) {
                    //拍照
                    getPermission(Manifest.permission.CAMERA)
                }
            }.show()
    }

    private fun getPermission(permission: String) {
        XXPermissions.with(activity).permission(permission).request(object : OnPermissionCallback {
            override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                if (permissions.contains(Manifest.permission.CAMERA)) {
                    openCamera()
                } else if (permissions.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    openGallery()
                }
            }

            override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                super.onDenied(permissions, doNotAskAgain)
            }
        })
    }

    /**
     * 从相册选择
     */
    fun openGallery() {
        PictureSelector.create(activity).openGallery(SelectMimeType.ofImage())
            .setImageEngine(CoilEngine()).isDisplayCamera(false).setMaxSelectNum(9 - count)
            .setCompressEngine { context: Context?, source: ArrayList<Uri>?, call: OnKeyValueResultCallbackListener? ->
                Luban.with(context).load(source)
                    .setCompressListener(object : OnNewCompressListener {
                        override fun onStart() {}
                        override fun onSuccess(source: String, compressFile: File) {
                            call?.onCallback(source, compressFile.absolutePath)
                        }

                        override fun onError(source: String, e: Throwable) {
                            call?.onCallback(source, null)
                        }
                    }).launch()
            }.forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    val pathList = mutableListOf<String>()
                    for (item in result) {
                        val realPath = item.realPath
                        val path = item.compressPath ?: realPath
                        pathList.add(path)
                    }
                    pictureSelectListener?.onPictureSelect(pathList)
                }

                override fun onCancel() {}
            })
    }

    /**
     * 调起相机拍照
     */
    @SuppressLint("QueryPermissionsNeeded")
    fun openCamera() {
        PictureSelector.create(activity).openCamera(SelectMimeType.ofImage())
            .setCompressEngine { context: Context?, source: ArrayList<Uri>?, call: OnKeyValueResultCallbackListener? ->
                Luban.with(context).load(source)
                    .setCompressListener(object : OnNewCompressListener {
                        override fun onStart() {}
                        override fun onSuccess(source: String, compressFile: File) {
                            call?.onCallback(source, compressFile.absolutePath)
                        }

                        override fun onError(source: String, e: Throwable) {
                            call?.onCallback(source, null)
                        }
                    }).launch()
            }.forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>) {
                    val pathList = mutableListOf<String>()
                    val path = result[0].compressPath ?: result[0].realPath
                    pathList.add(path)
                    pictureSelectListener?.onPictureSelect(pathList)
                }

                override fun onCancel() {}
            })
    }

    /**
     * 图片选定之后的回调监听
     */
    interface PictureSelectListener {
        fun onPictureSelect(imagePathList: MutableList<String>) //返回图片的路径
        fun throwError(e: Exception) //当错误时返回对应的异常
    }
}